<script setup>
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import http from '@/config/axios-config'

let imgPrompt = ref('')
let image = ref([])
let textPrompt = ref('')
let text = ref([])
let imgLoading = ref(false)
let textLoading = ref(false)
let textModel = ref('text-davinci-003')

let domain = 'http://127.0.0.1:3000'

const onSearchImg = () => {
  imgLoading.value = true
  http.get(domain + '/api/img', { params: { prompt: imgPrompt.value } }).then(res => {
    image.value = res.data
    imgLoading.value = false
  })
}

const onSearchText = () => {
  textLoading.value = true
  let value = ''
  if (text.value.length) {
    text.value.forEach(item => {
      value += 'Human:' + item.title + item.choices[0].replace(/<br>+/g, '\n') + '\n'
    })
  }
  value += 'Human:' + textPrompt.value
  http.get(domain + '/api/text', { params: { prompt: value, model: textModel.value } }).then(res => {
    if (res.msg) {
      message.error(res.msg)
    } else {
      let result = []
      res.choices.forEach(item => {
        let text = item.text.trimLeft('\n').replace(/\n+/g, '<br>')
        result.push(text)
      })
      text.value = text.value.concat([{
        title: textPrompt.value,
        choices: result
      }])
    }
    textLoading.value = false
    textPrompt.value = ''
  })
}

</script>

<template>
  <div class="wrapper">
    <h2>生成图片</h2>
    <div>
      <a-input-search
          style="width: 300px"
          v-model:value="imgPrompt"
          placeholder="prompt"
          enter-button
          :loading="imgLoading"
          @search="onSearchImg"
      />
    </div>
    <div class="img-box" v-if="image.length" style="margin-top: 10px">
      <a-image
          v-for="(item, idx) in image"
          :key="idx"
          :width="200"
          :src="item.url"
      />
    </div>
    <a-divider/>

    <h2>文字补全</h2>
    <div>
      <a-select v-model:value="textModel">
        <a-select-option value="text-ada-001">text-ada-001</a-select-option>
        <a-select-option value="text-babbage-001">text-babbage-001</a-select-option>
        <a-select-option value="text-curie-001">text-curie-001</a-select-option>
        <a-select-option value="text-davinci-003">text-davinci-003</a-select-option>
      </a-select>
      <a-input-search
          style="width: 300px"
          v-model:value="textPrompt"
          placeholder="prompt"
          enter-button
          :loading="textLoading"
          @search="onSearchText"
      />
    </div>
    <div class="text-box" v-if="text.length">
      <div v-for="(item, idx) in text" :key="idx">
        <h2>问：{{ item.title }}</h2>
        <p v-for="(c, i) in item.choices" :key="i" v-html="c"></p>
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>
.text-box, .img-box {
  margin-top: 10px
}

.text-box {
  div {
    padding: 10px;
    border-bottom: 1px solid #eee;
  }

  p {
    padding: 5px 10px;
    border-bottom: 1px solid #fefefe;
  }
}
</style>
